﻿using EkStudio.com.bean.xml.ProjectMenu;
using EkStudio.com.common.unit;
using EkStudio.com.ui.unitbill.property.Event;
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using System.Xml;

namespace EkStudio.com.ui.form
{
    public partial class MenuMapingForm : DevExpress.XtraEditors.XtraForm
    {
        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(MenuMapingForm));

        private ProjectRootPanel RootPanel = null;

        private DataTable data = null;

        private delegate void UpdateStatusDelegate(string key, string xml);

        private bool loading = false;

        public MenuMapingForm(ProjectRootPanel root)
        {
            InitializeComponent();
            RootPanel = root;
            //初始化相关
            data = new DataTable("TableName");
            data.Columns.Add("DataModuleName", typeof(string));
            data.Columns.Add("DataModuleKey", typeof(string));
            GridMenuControl.DataSource = data;
        }

        new public DialogResult ShowDialog()
        {
            data.Rows.Clear();
            GridMenuView.RefreshData();
            //加载目录
            ListMenu.Items.Clear();
            ProjectMenuItem menu = RootPanel.MenuItem;
            if (menu.Business != null && menu.Business.Modules != null && menu.Business.Modules.Count > 0)
            {
                foreach(ProjectMenuModGroup gp in menu.Business.Modules)
                {
                    ListMenu.Items.Add(gp.Caption);
                }
            }
            BtnSubmit.Enabled = false;
            return base.ShowDialog();
        }

        

        private void ListMenu_SelectedIndexChanged(object sender, EventArgs e)
        {
            data.Rows.Clear();
            GridMenuView.RefreshData();
            BtnSubmit.Enabled = false;
            if (!loading)
            {
                loading = true;
                Dictionary<string, string> param = new Dictionary<string, string>();
                param.Add("loadType", "1");
                param.Add("loadNode", (string)ListMenu.SelectedItem);
                RootPanel.Http.AsyncPost(ProjectUtil.HTTP_ATTACH_LIST_URL, param, "", CallBackFunction);
            }
        }

        /// <summary>
        /// 异步回調函数，当前方法会在异步线程执行 要转成同步
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CallBackFunction(object sender, PropertyDataEvent e)
        {
            //异步转同步
            this.BeginInvoke(new UpdateStatusDelegate(TbCallEvent), new object[] { e.Key, (string)e.Value });
        }

        private void TbCallEvent(string key, string xml)
        {
            if (key == "OK")
            {
                XmlDocument doc = new XmlDocument();
                try
                {
                    doc.LoadXml(xml);
                    XmlElement root = doc.DocumentElement;
                    XmlNodeList list = root.SelectNodes("item");
                    if (list != null && list.Count > 0)
                    {
                        foreach (XmlNode node in list)
                        {
                            string name = node.Attributes["caption"].Value;
                            string date = node.Attributes["bill"].Value;
                            DataRow row = data.NewRow();
                            row["DataModuleName"] = name;
                            row["DataModuleKey"] = date;
                            data.Rows.Add(row);
                        }
                    }
                }
                finally
                {
                    GridMenuView.RefreshData();
                }
            }
            else
            {
                RootPanel.ShowAlert("附件", "加载目录失败");
                logger.Error("加载目录失败");
            }
            loading = false;
        }
        /// <summary>
        /// 上移
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnMoveUp_Click(object sender, EventArgs e)
        {
            int index = GridMenuView.FocusedRowHandle;
            if (index > 0)
            {
                BtnSubmit.Enabled = true;
                int PevIndex = index - 1;
                string caption = (string)data.Rows[PevIndex]["DataModuleName"];
                string bill = (string)data.Rows[PevIndex]["DataModuleKey"];
                //修改当条记录为当前内容
                data.Rows[PevIndex]["DataModuleName"] = data.Rows[index]["DataModuleName"];
                data.Rows[PevIndex]["DataModuleKey"] = data.Rows[index]["DataModuleKey"];
                //修改当前记录为上条内容
                data.Rows[index]["DataModuleName"] = caption;
                data.Rows[index]["DataModuleKey"] = bill;

                GridMenuView.RefreshRow(PevIndex);
                GridMenuView.RefreshRow(index);
                GridMenuView.FocusedRowHandle = PevIndex;
            }
        }

        private void BtnMoveDown_Click(object sender, EventArgs e)
        {
            int index = GridMenuView.FocusedRowHandle;
            if (index >= 0 && index < data.Rows.Count - 1)
            {
                BtnSubmit.Enabled = true;
                int NextIndex = index + 1;
                string caption = (string)data.Rows[NextIndex]["DataModuleName"];
                string bill = (string)data.Rows[NextIndex]["DataModuleKey"];
                //修改下条记录为当前内容
                data.Rows[NextIndex]["DataModuleName"] = data.Rows[index]["DataModuleName"];
                data.Rows[NextIndex]["DataModuleKey"] = data.Rows[index]["DataModuleKey"];
                //修改当前记录为下条内容
                data.Rows[index]["DataModuleName"] = caption;
                data.Rows[index]["DataModuleKey"] = bill;
                GridMenuView.RefreshRow(NextIndex);
                GridMenuView.RefreshRow(index);
                GridMenuView.FocusedRowHandle = NextIndex;
            }
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            if (BtnSubmit.Enabled&& ULabel.Comfirm_Ok_Cancel("当前存在修改，您确认放弃保存吗？") == DialogResult.OK)
            {
                BtnSubmit.Enabled = false;
            }
        }
        /// <summary>
        /// 提交更改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSubmit_Click(object sender, EventArgs e)
        {
            if (data.Rows.Count > 0)
            {
                string MenuName = ListMenu.SelectedItem as string;
                System.Text.StringBuilder MenuList = new System.Text.StringBuilder();
                foreach (DataRow row in data.Rows)
                {
                    if (MenuList.Length > 0) MenuList.Append(",");
                    MenuList.Append(row["DataModuleKey"]);
                }
                if (MenuList.Length > 0)
                {
                    Dictionary<string, string> param = new Dictionary<string, string>();
                    param.Add("menuName", MenuName);
                    param.Add("menuList", MenuList.ToString());
                    RootPanel.Http.PostHttp(ProjectUtil.HTTP_MENUMAP_URL, param, "");
                }
            }
        }
    }
}